// code, 200: 请求成功; 400: 登录账号或密码错误; 401: 用户未登录，或登录已过期

import axios from 'axios'
import * as util from './util'
import { MessageBox } from 'element-ui'
import router from '@/router'
import store from '@/store'

const DOMAIN = 'http://localhost:7001'
const instance = axios.create();

/**
 * GET请求
 * @param {*} url 请求地址
 * @param {*} params 请求参数
 */
export const get = async (url, params) => {
  const config = { headers: {} }
  const userId = util.localStorage.get('userId')
  if (userId) {
    config.headers['user-id'] = userId
  }
  return new Promise(async (resolve, reject) => {
    await instance.get(`${DOMAIN}${url}`, {
      params,
      headers: config.headers
    }).then(result => {
      const { code } = result.data
      if (code === 401) {
        loginFail(code, result.data)
      } else {
        resolve(result.data)
      }
    }).catch(error => {
      reject(error)
    })
  })
}
/**
 * POST请求
 * @param {*} url 请求地址
 * @param {*} params 请求参数
 */
export const post = async (url, params) => {
  const config = { headers: {} }
  const userId = util.localStorage.get('userId')
  if (userId) {
    config.headers['user-id'] = userId
  }
  return new Promise(async (resolve, reject) => {
    await instance.post(`${DOMAIN}${url}`, params, config).then(result => {
      const { code } = result.data
      if (code === 401) {
        loginFail(code, result.data)
      } else {
        resolve(result.data)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

function loginFail() {
  MessageBox.alert('登录已失效，请重新登录', '提示', {
    confirmButtonText: '确定',
    callback: async () => {
      await store.dispatch('logout')
      router.push({
        name: 'Login'
      })
    }
  })
}